const fs = require('fs');
const path = require('path');
const dev = require('./env/dev');
const test = require('./env/test');
const prep = require('./env/prep');
const prod = require('./env/prod');

const ENV_PATH_MAP = {
  dev,
  test,
  prep,
  prod
};

function getNpmEnv(npmLifeCycle) {
  return npmLifeCycle.split(':');
}

function getNpmEnvTarget(npmLifeCycle) {
  const { 1: target } = getNpmEnv(npmLifeCycle);
  return target;
}

function getEnvConfig(npmLifeCycle) {
  const targetEnv = getNpmEnvTarget(npmLifeCycle);
  const envConfig = ENV_PATH_MAP[targetEnv] || ENV_PATH_MAP.dev;
  return envConfig;
}

const [targetAction, targetEnv] = getNpmEnv(process.env.npm_lifecycle_event);

const env = {
  TARGET_ACTION: targetAction,
  TARGET_ENV: targetEnv,
  ...getEnvConfig(process.env.npm_lifecycle_event)
};

function CleanJsMapPlugin() {
  function removeMapFile(root) {
    if (!fs.existsSync(root)) return;
    const stat = fs.statSync(root);
    if (stat.isFile()) {
      const filename = path.basename(root);
      if (/\.map$/.test(filename)) {
        fs.unlinkSync(root);
      }
    } else if (stat.isDirectory()) {
      const files = fs.readdirSync(root);
      files.forEach(name => removeMapFile(path.join(root, name)));
    }
  }

  this.apply = function apply(compiler) {
    compiler.hooks.afterEmit.tap('CleanJsMapPlugin', () => {
      removeMapFile(path.join(__dirname, '.nuxt'));
    });
  };
}

function CleanJsMapModule() {
  this.nuxt.hook('webpack:config', webpackConfigs => {
    const config = webpackConfigs[webpackConfigs.length - 1];
    if (!config.plugins) config.plugins = [];
    if (config.plugins.every(p => !(p instanceof CleanJsMapPlugin))) {
      config.plugins.push(new CleanJsMapPlugin());
    }
  });
}

module.exports = {
  loading: true,
  head: {
    titleTemplate: '',
    meta: [
      { charset: 'utf-8' },
      {
        name: 'viewport',
        content:
          'width=device-width, initial-scale=1, maximum-scale=1, user-scalable=no'
      }
    ],
    link: [
      { rel: 'icon', type: 'image/x-icon', href: '/ico/tnaot_favicon.ico' },
      { rel: 'apple-touch-icon', sizes: '60x60', href: '/img/icon-60.png' },
      { rel: 'apple-touch-icon', sizes: '120x120', href: '/img/icon-120.png' },
      { rel: 'apple-touch-icon', sizes: '256x256', href: '/img/logo-256.png' },
      { rel: 'apple-touch-icon-precomposed', href: '/img/logo-256.png' },
      { rel: 'shortcut icon', type: 'image/png', href: '/img/favicon-32.ico' }
    ],
    script: [
      { src: '/js/flexible.js', type: 'text/javascript', charset: 'utf-8' },
      {
        src: '/js/third_party.js',
        type: 'text/javascript',
        charset: 'utf-8',
        body: true,
        async: true
      }
    ]
  },
  css: ['@/assets/css/common.css'],
  build: {
    analyze: false,
    vendor: ['axios', 'vant'],
    postcss: [
      require('postcss-px2rem-exclude')({
        remUnit: 75,
        exclude: /node_modules|pc/i
      })
    ]
  },
  plugins: [
    { src: '~/plugins/bridge', ssr: false },
    { src: '~/plugins/vant', ssr: true },
    { src: '~/plugins/i18n' },
    { src: '~/plugins/seo', ssr: true },
    { src: '~/plugins/vue-clipboard2', ssr: false },
    {
      src: '~/plugins/filter.js',
      ssr: true
    }
  ],
  modules: ['@nuxtjs/axios', '@nuxtjs/sentry', CleanJsMapModule],
  isDev: env.TARGET_ACTION === 'dev',
  sentry: {
    dsn: env.SENTRY_DSN,
    config: {
      environment: env.TARGET_ENV
    },
    publishRelease: env.TARGET_ACTION === 'build' && env.TARGET_ENV !== 'dev',
    webpackConfig: {
      include: ['.nuxt/dist/'],
      deploy: {
        env: env.TARGET_ENV
      }
    },
    extractCSS: true,
    optimizeCss: true
  },
  axios: {
    baseURL: env.SERVER_API
  },
  env,
  router: {
    middleware: ['i18n', 'axios'],
    extendRoutes(routes, resolve) {
      const defaultLangRoutes = [];
      routes.forEach(item => {
        if (item.name === 'lang' || item.name.substr(0, 5) === 'lang-') {
          const route = {};
          if (item.name.length === 4) {
            route.name = 'index';
            route.path = '/';
          } else {
            route.name = item.name.substr(5);
            route.path = '/' + route.name;
          }
          route.component = item.component;
          route.chunkName = item.chunkName;
          defaultLangRoutes.push(route);
        }
      });
      defaultLangRoutes.forEach(item => {
        routes.unshift(item);
      });
    }
  },
  render: {
    resourceHints: true
  }
};
